﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static System.Net.Mime.MediaTypeNames;

public class EditPhotoItem : MonoBehaviour
{
    int m_texId;

    public NetworkImage rawImage;

    public GameObject closeBtn;

    float rawImageOriginalSize;

    Action<int, Tex> m_onLoadedTex;
    Action<int> m_onRemoveTex;

    Texture2D m_Texture;
    void Awake()
    {
        //rawImageOriginalSize = rawImage.GetComponent<RectTransform>().rect.width;
        //rawImage.texture = null;
    }
    // Start is called before the first frame update
    void Start()
    {

    }
    public void Init(int id,string tex, Action<int, Tex> onLoadedTex, Action<int> onRemoveTex)
    {
        m_texId = id;
        m_onLoadedTex = onLoadedTex;
        m_onRemoveTex = onRemoveTex;

        this.rawImage.Init(tex);

    }
    void SetTexture(RawImage rawImage, Texture2D texture)
    {
        if (m_Texture)
            DestroyImmediate(m_Texture);
        m_Texture = texture;

        if (rawImageOriginalSize <= 0)
            rawImageOriginalSize = rawImage.GetComponent<RectTransform>().rect.width;

        UnityFunctions.SetRawImage(rawImage, texture, rawImageOriginalSize);

        if (texture != null)
        {
            rawImage.gameObject.SetActive(true);
            closeBtn.SetActive(true);
        }
        else
        {
            rawImage.gameObject.SetActive(false);
            closeBtn.SetActive(false);
        }
    }

    public void OnClickClose()
    {
        int id = m_texId;
        RequestServerController.instance.ReqUploadPhotos(id, null, (ret) =>
        {
            rawImage.Init("");
            //if (rawImage.texture != null)
            //    DestroyImmediate(rawImage.texture);

            //SetTexture(rawImage, null);

            this.m_onRemoveTex?.Invoke(id);
        });
    }


    public void OnClickUploadImg()
    {
        int id = this.m_texId;

        LoadImg((newtexture) =>
        {
            OnImageLoaded(id, newtexture);
        });

        //int maxSize = EditIconUI.maxSize;
        //NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
        //{
        //    Debug.Log("Image path: " + path);
        //    if (path != null)
        //    {
        //        Texture2D texture = NativeGallery.LoadImageAtPath(path, maxSize, false, false);
        //        if (texture == null)
        //        {
        //            Debug.Log("Couldn't load texture from " + path);
        //            return;
        //        }

        //        if (texture.width > maxSize || texture.height > maxSize)
        //        {
        //            float rate = 1;
        //            if (texture.width > texture.height)
        //            {
        //                rate = texture.width / (float)maxSize;
        //            }
        //            else
        //            {
        //                rate = texture.height / (float)maxSize;
        //            }
        //            Texture2D newtexture = EditIconUI.ScaleTexture(texture, (int)(texture.width / rate), (int)(texture.height / rate));
        //            GameDebug.Log($"texture width:{texture.width}  height:{texture.height}  new width:{newtexture.width}  new height:{newtexture.height}  rate:{rate}");
        //            OnImageLoaded(id, newtexture);

        //            DestroyImmediate(texture);
        //        }
        //        else
        //        {
        //            OnImageLoaded(id, texture);
        //        }
        //    }
        //});
    }

    public static void LoadImg(Action<Texture2D> onImgLoaded)
    {
        int maxSize = EditIconUI.maxSize;
        NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
        {
            Debug.Log("Image path: " + path);
            if (path != null)
            {
                Texture2D texture = NativeGallery.LoadImageAtPath(path, maxSize, false, false);
                if (texture == null)
                {
                    Debug.Log("Couldn't load texture from " + path);
                    return;
                }

                if (texture.width > maxSize || texture.height > maxSize)
                {
                    float rate = 1;
                    if (texture.width > texture.height)
                    {
                        rate = texture.width / (float)maxSize;
                    }
                    else
                    {
                        rate = texture.height / (float)maxSize;
                    }
                    Texture2D newtexture = ScaleTexture(texture, (int)(texture.width / rate), (int)(texture.height / rate));
                    GameDebug.Log($"texture width:{texture.width}  height:{texture.height}  new width:{newtexture.width}  new height:{newtexture.height}  rate:{rate}");
                    onImgLoaded?.Invoke(newtexture);

                    DestroyImmediate(texture);
                }
                else
                {
                    onImgLoaded?.Invoke(texture);
                }
            }
        });

        Debug.Log("Permission result: " + permission);
    }
    public static Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
    {
        Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
        Color[] rpixels = result.GetPixels(0);
        float incX = ((float)1 / source.width) * ((float)source.width / targetWidth);
        float incY = ((float)1 / source.height) * ((float)source.height / targetHeight);
        for (int px = 0; px < rpixels.Length; px++)
        {
            rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
        }

        result.SetPixels(rpixels, 0);
        result.Apply();
        return result;
    }
    void OnImageLoaded(int id,Texture2D texture)
    {
        Tex tex = new Tex();
        tex.texWidth = texture.width;
        tex.texHeight = texture.height;
        tex.tex = texture.EncodeToJPG(80);

        RequestServerController.instance.ReqUploadPhotos(id, tex, (url) =>
        {
            rawImage.Init(url);
            //if (rawImage.texture != null)
            //    DestroyImmediate(rawImage.texture);

            //SetTexture(rawImage, texture);

            this.m_onLoadedTex?.Invoke(id, tex);
        });
    }


    // Update is called once per frame
    void Update()
    {

    }
    void OnDestroy()
    {
        //if (rawImage.texture != null) DestroyImmediate(rawImage.texture);
    }

}
